package com.zrrd.straw1.service.impl;

import com.zrrd.straw1.entity.Answer;
import com.zrrd.straw1.entity.Question;
import com.zrrd.straw1.entity.User;
import com.zrrd.straw1.mapper.AnswerMapper;
import com.zrrd.straw1.mapper.QuestionMapper;
import com.zrrd.straw1.mapper.UserMapper;
import com.zrrd.straw1.service.IAnswerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.straw1.vo.AnswerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zrrd
 * @since 2024-03-03
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements IAnswerService {
    @Autowired
    AnswerMapper answerMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    QuestionMapper questionMapper;

    @Override
    //Spring框架提供的事务管理注解，原理是 Spring AOP
    @Transactional
    public Answer saveAnswer(AnswerVo answerVo, String username) {
        User user = userMapper.findUserByUsername( username );
        Answer answer = new Answer()
                .setContent(answerVo.getContent())
                .setUserId(user.getId())
                .setUserNickName(user.getNickName())
                .setQuestionId(answerVo.getQuestionId())
                .setIsAccepted(0)
                .setGmtCreate(LocalDateTime.now())
                .setGmtModified(LocalDateTime.now());
        int num = answerMapper.insert( answer );
        if( num != 1) throw ServiceException.busy();
        return answer ;
    }

    @Override
    public List<Answer> getAnswersByQuestionId(Integer questionId) {
        //业务层加分析
        if( questionId == null ){
            //方法中断（结束），走Java异常机制，达到流程跳转的目的。
            throw ServiceException.notFound("没有问题ID，无法查询解答");
        }

        List<Answer> answers = answerMapper.getAnswersByQuestionId( questionId );
        return answers;
    }


    //事务注解
    @Transactional
    @Override
    public boolean accept(Integer answerId, String username) {
        Answer  answer = answerMapper.selectById(answerId);
        User user = userMapper.findUserByUsername(username);
        //不重复采纳
        if(answer.getIsAccepted()==1){
            return false;
        }
        Question question = questionMapper.selectById(answer.getQuestionId());
        //不是问题发布者，返回false
        if(question.getUserId()==user.getId()){
            return false;
        }
        Integer num = answerMapper.updateAcceptStatus(answerId, 1);

        if(num!=1){
            throw ServiceException.busy();
        }
        //如果采纳成功 接着把问题状态修改了
        num = questionMapper.updateStatus(question.getId(), Question.SOLVED);
        if(num!=1) throw  ServiceException.busy();
        return true;
    }
}
